package com.example.caoben_back.contoller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.caoben_back.entity.po.Like;
import com.example.caoben_back.entity.po.User;
import com.example.caoben_back.entity.vo.Result;
import com.example.caoben_back.service.ILikeService;
import com.example.caoben_back.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/like")
public class LikeController {

    @Autowired
    private ILikeService likeService;
    
    // 点赞
    @PostMapping("/add")
    public Result<Boolean> addLike(@RequestBody Like likeParams,
                                  HttpServletRequest request) {
        // 从token中解析用户信息
        User user = TokenUtil.getUserFromRequest(request);
        if (user == null) {
            return Result.fail("用户未登录");
        }
        Integer userId = user.getUserId();
        
        Like like = new Like();
        like.setLikerId(userId);
        like.setLikedUserId(likeParams.getLikedUserId());
        like.setLikeType(likeParams.getLikeType());
        like.setCreateTime(LocalDateTime.now());
        boolean save = likeService.save(like);
        return Result.success(save);
    }

    // 取消点赞
    @PostMapping("/cancel")
    public Result<Boolean> cancelLike(@RequestBody Like likeParams,
                                     HttpServletRequest request) {
        // 从token中解析用户信息
        User user = TokenUtil.getUserFromRequest(request);
        if (user == null) {
            return Result.fail("用户未登录");
        }
        Integer userId = user.getUserId();
        
        boolean remove = likeService.remove(new QueryWrapper<Like>()
                .eq("liker_id", userId)
                .eq("liked_user_id", likeParams.getLikedUserId())
                .eq("like_type", likeParams.getLikeType()));
        return Result.success(remove);
    }

    // 检查是否已点赞
    @GetMapping("/check")
    public Result<Map<String, Boolean>> checkLike(@RequestParam Integer targetId,
                                                 @RequestParam Integer likeType,
                                                 HttpServletRequest request) {
        // 从token中解析用户信息
        User user = TokenUtil.getUserFromRequest(request);
        if (user == null) {
            return Result.fail("用户未登录");
        }
        Integer userId = user.getUserId();
        
        Like like = likeService.getOne(new QueryWrapper<Like>()
                .eq("liker_id", userId)
                .eq("liked_user_id", targetId)
                .eq("like_type", likeType));
        Map<String, Boolean> data = new HashMap<>();
        data.put("isLike", like != null);
        return Result.success(data);
    }
}